﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace LanShellManager.Models
{
    internal class MachineRepository:IMachineRepository
    {
        private ShellCommandsEntities entities;

        public MachineRepository()
        {
            entities = new ShellCommandsEntities();
        }

        public List<MachineVm> GetMachines()
        {
            List<Machine> machines= entities.Machines.ToList();
            List<MachineVm> result = new List<MachineVm>();
            foreach (var machine in machines)
            {
                result.Add(new MachineVm(){Id=machine.Id, Name = machine.Name, IpAddress = machine.IpAddress});
            }
            return result;
        }

        public MachineVm Find(int id)
        {
            Machine machine=entities.Machines.FirstOrDefault(m=> m.Id==id);
            MachineVm result = new MachineVm();
            result.Id = machine.Id;
            result.Name = machine.Name;
            result.IpAddress = machine.IpAddress;
            return result;
        }

        public void Delete(int id)
        {
            Machine machine=entities.Machines.FirstOrDefault(m=> m.Id==id);
            entities.Machines.Remove(machine);
            entities.SaveChanges();
        }

        public void Update(MachineVm machinevm)
        {
            Machine machine = entities.Machines.FirstOrDefault(m => m.Id == machinevm.Id);
            machine.Name=machinevm.Name;
            machine.IpAddress = machinevm.IpAddress;
            entities.SaveChanges();
        }

        public void Add(MachineVm machine)
        {
            entities.Machines.Add(new Machine(){Id=machine.Id, Name = machine.Name, IpAddress = machine.IpAddress});
            entities.SaveChanges();
        }
    }
}